package com.saifan.wyy_ov.ui.property;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.data.bean.MatterRequsetBean;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IViewOnClick;
import com.saifan.wyy_ov.ui.album.ui.PhotoAlbumActivity;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.NoScrollGridView;
import com.saifan.wyy_ov.utils.CameraUtil;
import com.saifan.wyy_ov.utils.DateTimePickUtils;
import com.saifan.wyy_ov.utils.DialogUtil;
import com.saifan.wyy_ov.utils.FileUtils;
import com.saifan.wyy_ov.utils.LogUtil;
import com.saifan.wyy_ov.utils.PictureUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015-05-07 20:18
 * @descrption 报事报修
 */
public class RepairActivity extends BaseActivity {


    private Toolbar toolbar;
    MatterRequsetBean requsetBean;
    private EditText BSQDDZ;
    private EditText BSQDLXR;
    private EditText BSQDLXDH;
    private EditText BSQDYYSJ;
    private EditText BSQDBSLR;

    private RoomInfoBean roomInfoBean;

    private NoScrollGridView picgrid;//照片集

    private ArrayList<String> selectList;
    private CommentsPicAdapter adapter;
    private final int SELECT_IMG = 0;
    private final int SELECT_PHOTO_TAKEPHOTO = 1;
    private static final int CHOSE_CONTACTS = 1234;
    private int selectPostion = 0;
String picName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        roomInfoBean = getRoomInfoBean();
        selectList = new ArrayList<String>();

        setContentView();
        requsetBean = new MatterRequsetBean();

    }

    private void setContentView() {
        setContentView(R.layout.activity_repair);
        this.picgrid = (NoScrollGridView) findViewById(R.id.pic_grid);

        this.BSQDBSLR = (EditText) findViewById(R.id.BSQD_BSLR);
        this.BSQDYYSJ = (EditText) findViewById(R.id.BSQD_YYSJ);
        this.BSQDLXDH = (EditText) findViewById(R.id.BSQD_LXDH);
        this.BSQDLXR = (EditText) findViewById(R.id.BSQD_LXR);
        this.BSQDDZ = (EditText) findViewById(R.id.BSQD_DZ);

        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        BSQDDZ.setText(StringUtil.returnShow(roomInfoBean.getWYFJDA_FJMC()));
        BSQDLXDH.setText(StringUtil.returnShow(roomInfoBean.getWYKHDA_SJ()));
        BSQDLXR.setText(StringUtil.returnShow(roomInfoBean.getWYKHDA_KHMC()));
        adapter = new CommentsPicAdapter(selectList, RepairActivity.this);
        picgrid.setAdapter(adapter);
        picgrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (selectList.size() < 5) {
                    selectPostion = position - 1;
                    showSelectImgDialog(position == 0 ? false : true, position - 1);
                } else {
                    selectPostion = position;
                    showSelectImgDialog(true, position);
                }
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_repair, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public String initParams() {
        requsetBean.setBSQD_BSLR(BSQDBSLR.getText().toString());
        try {
            requsetBean.setBSQD_YYSJ(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(BSQDYYSJ.getText().toString().trim()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        requsetBean.setBSQD_CJSJ(new Date());
        requsetBean.setBSQD_LXR(BSQDLXR.getText().toString());
        requsetBean.setBSQD_LXDH(BSQDLXDH.getText().toString());
        requsetBean.setBSQD_LX("业主");
        requsetBean.setBSQD_XMLX(1);
        requsetBean.setBSQD_FKGXWJ(roomInfoBean.getFKGX_ZJ());
        requsetBean.setBSQD_DZ(roomInfoBean.getWYFJDA_FJMC());
        requsetBean.setXMBS(roomInfoBean.getXMBS());
        return new Gson().toJson(requsetBean);

    }

    public void matterSubmit(View view) {
        if (isEmpty(BSQDLXR)) {
            ToastUtil.showToast(this, "联系人不能为空");
            BSQDLXR.setFocusable(true);
            return;
        }
        if (isEmpty(BSQDLXDH)) {
            BSQDLXDH.setFocusable(true);
            ToastUtil.showToast(this, "联系电话不能为空");
            return;
        }
        if (isEmpty(BSQDYYSJ)) {

            ToastUtil.showToast(this, "预约时间不能为空");
            showDatePick();
            return;
        }
        if (isEmpty(BSQDBSLR)) {
            BSQDBSLR.setFocusable(true);
            ToastUtil.showToast(this, "内容不能为空");
            return;
        }


        GetData getData = new GetData();
        RequestParams params = new RequestParams();
        params.addBodyParameter(Api.Matter.MATTER, initParams());

        for (int i = 0; i < selectList.size(); i++) {
            File file = new File(PictureUtil.getCompressBitmap(selectList.get(i)));
            if (file.exists()) {
                LogUtil.i(FileUtils.getFileSize(FileUtils.getFileSize(file.getPath())));
                params.addBodyParameter(file.getName(), file);
            }

        }


        getData.getData(Api.Matter.MATTER_SUBMIT, params, new RequestCallBack<String>() {

            @Override
            public void onStart() {
                super.onStart();
                DialogUtil.showProgressDialog(RepairActivity.this, "正在提交");
            }

            @Override
            public void onCancelled() {
                super.onCancelled();
                LogUtil.i("取消请求");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                if (!StringUtil.isNullOrEmpty(responseInfo.result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(responseInfo.result.toString());
                        String code = jsonObject.getString("Code");
                        if (code.equals("200")) {
                            ToastUtil.showToast(RepairActivity.this, "提交成功");
                            DialogUtil.closeProgressDialog();
                            finish();

                        } else if (code.equals("203")) {
                            DialogUtil.closeProgressDialog();
                            ToastUtil.showToast(RepairActivity.this, getString(R.string.login_error_tip));
                        } else if (code.equals("204")) {
                            DialogUtil.closeProgressDialog();
                            ToastUtil.showToast(RepairActivity.this, "用户名已存在 !");
                        } else if (code.equals("202")) {
                            DialogUtil.closeProgressDialog();
                            ToastUtil.showToast(RepairActivity.this, "保存失败，信息未做修改 !");
                        } else {
                            LogUtil.e(code);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    LogUtil.e("ServerError");
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                LogUtil.i(s);
                ToastUtil.showToast(RepairActivity.this, getString(R.string.network_error));
                DialogUtil.closeProgressDialog();
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                super.onLoading(total, current, isUploading);
                LogUtil.i("onLoading" + current + "-------------------" + total);
            }
        });

    }

    public void specialDate(View view) {
        showDatePick();
    }

    public void showDatePick() {
        DateTimePickUtils.show(this, new IViewOnClick() {
            @Override
            public void onClick(Object... object) {
                BSQDYYSJ.setText(object[0].toString());
            }
        }, new Date());
    }

    public void getContacts(View view) {

        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS }, CHOSE_CONTACTS);
                return;
            }else {
                Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(i, CHOSE_CONTACTS);
            }
        }else {
            Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(i, CHOSE_CONTACTS);
        }


    }


    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
        }
        if (id == R.id.history_record) {
            Intent intent = new Intent();
            intent.setClass(this, RepairRecoderActivity.class);
            startActivity(intent);

        }
        return super.onOptionsItemSelected(item);
    }


    public void selectImg() {
        storePermission(SELECT_IMG);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == SELECT_IMG) {
            if (resultCode == RESULT_OK) {
                this.selectList = data.getStringArrayListExtra("data");
                adapter.list = selectList;
                adapter.notifyDataSetChanged();
            }
        } else if (requestCode == SELECT_PHOTO_TAKEPHOTO) {
            if (resultCode == RESULT_OK) {

                Bitmap bitmap = data.getParcelableExtra("data") ;
                File file = FileUtils. bitmapToFile(bitmap);
                FileUtils.toAlbum(this,file);
                picName=file.getAbsolutePath();
                if (selectPostion == -1) {
                    this.selectList.add(picName);
                } else {
                    this.selectList.set(selectPostion, picName);
                }
                adapter.list = selectList;
                adapter.notifyDataSetChanged();
            }
        } else if (requestCode == CHOSE_CONTACTS) {
            if (!(resultCode == RESULT_OK)) {
                return;
            }
            if (data == null) {
                return;
            }
            Uri uri = data.getData();
            String name = "";
            String number = "";
            Cursor cursor = getContentResolver().query(uri, null, null, null,
                    null);
            if (cursor != null) {
                cursor.moveToFirst();
                int contactId = Integer.valueOf(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)));
                name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                    if (phones.moveToFirst()) {
                        //遍历所有的电话号码
                        number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                    }
                }
//
                BSQDLXDH.setText(number.replace(" ",""));
                BSQDLXR.setText(name);
            }


        }
    }

    //显示选择图片的对话框
    private void showSelectImgDialog(boolean hasDelete, final int deletePostion) {
        String[] items;
        if (hasDelete)
            items = new String[]{"从相册中选择", "拍照", "删除"};
        else
            items = new String[]{"从相册中选择", "拍照"};


        AlertDialog dialog = new AlertDialog.Builder(RepairActivity.this)
                .setTitle("选择图片")

                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            selectImg();
                        } else if (which == 2) {
                            selectList.remove(deletePostion);
                            adapter.list = selectList;
                            adapter.notifyDataSetChanged();
                        } else {
                            cammerPermission(SELECT_PHOTO_TAKEPHOTO);
                        }
                        dialog.dismiss();
                    }
                })
                .show();
    }

    public void cammerPermission(int position) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, position);
                return;
            } else {


                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, SELECT_PHOTO_TAKEPHOTO);


            }
        }
        else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, SELECT_PHOTO_TAKEPHOTO);
        }

    }

    public void storePermission(int position) {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, position);
                return;
            } else {
                Intent intent = new Intent(RepairActivity.this, PhotoAlbumActivity.class);
                intent.putStringArrayListExtra("data", selectList);
                RepairActivity.this.startActivityForResult(intent, SELECT_IMG);
            }
        }else {
            Intent intent = new Intent(RepairActivity.this, PhotoAlbumActivity.class);
            intent.putStringArrayListExtra("data", selectList);
            RepairActivity.this.startActivityForResult(intent, SELECT_IMG);
        }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
       if (requestCode==SELECT_PHOTO_TAKEPHOTO){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, SELECT_PHOTO_TAKEPHOTO);


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用摄像头", Toast.LENGTH_SHORT)
                        .show();

            }
        }
        else if (requestCode==SELECT_IMG){

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Intent intent = new Intent(RepairActivity.this, PhotoAlbumActivity.class);
                intent.putStringArrayListExtra("data", selectList);
                RepairActivity.this.startActivityForResult(intent, SELECT_IMG);


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用本地存储读写", Toast.LENGTH_SHORT)
                        .show();

            }
        }else if (requestCode==CHOSE_CONTACTS){

           if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               // Permission Granted
               Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
               startActivityForResult(i, CHOSE_CONTACTS);


           } else {
               // Permission Denied
               Toast.makeText(this, "您禁用了读取通讯录权限", Toast.LENGTH_SHORT)
                       .show();

           }
       }

    }

}
